import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import persist from 'vuex-persist'

export default new Vuex.Store({
  state: {
    shop: []
  },
  mutations: {
    //添加商品
    add(state, obj) {
      console.log(obj);
      let flag=true
      state.shop.forEach((item,index)=>{
        if(obj.id==item.id){
          item.num+=obj.num
          flag=false
        }
      })
      if(flag==true){
        state.shop.push(obj)
      }
    },
    //单删除
    del(state,id){
      state.shop.forEach((item,index)=>{
        if(item.id==id){
          state.shop.splice(index,1)
        }
      })
    },
    //改变购物车数量
    changeNum(state,obj){
      state.shop.forEach(item=>{
        if(item.id==obj.id){
          item.num=obj.num;
        }
      })
    },
    //选择
    delChk(state,obj){
      console.log(obj);
      state.shop=state.shop.filter((item,index)=>{
        if(obj.indexOf(item.id)==-1){
          return item
        }
      })
    }
  },
  actions: {},
  modules: {},
  plugins: [
    new persist({
      storage: window.localStorage,
    }).plugin,
  ],
})